package cn.com.jslh.nfcpro;

import android.Manifest;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;

import cn.com.jslh.nfcpro.adapter.JiLuAdapter;
import cn.com.jslh.nfcpro.base.BaseActivity;
import cn.com.jslh.nfcpro.base.BaseRecycleViewAdapter;
import cn.com.jslh.nfcpro.bean.JiLuBean;
import cn.com.jslh.nfcpro.util.ByteUtil;
import cn.com.jslh.nfcpro.util.ExcelUtils;
import cn.com.jslh.nfcpro.util.TimeUtil;
import cn.com.jslh.nfcpro.util.database.DBHelper;
import cn.com.jslh.nfcpro.util.database.DataBaseUtil;

public class MainActivity extends BaseActivity {

    private RecyclerView mNfcRecycleViewRecyclerView;
    private JiLuAdapter jiluAdapter;
    private NfcAdapter mNfcAdapter;
    private PendingIntent pi;
    private ArrayList<Object> datas;

    @Override
    public void initViews() {
        setContentView(R.layout.activity_main);
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        mNfcRecycleViewRecyclerView = (RecyclerView) findViewById(R.id.nfcRecycleView);
        mNfcRecycleViewRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        mNfcRecycleViewRecyclerView.addItemDecoration(new DividerItemDecoration(this, OrientationHelper.VERTICAL));
        jiluAdapter = new JiLuAdapter();
        mNfcRecycleViewRecyclerView.setAdapter(jiluAdapter);
    }

    @Override
    public void initDatas() {
        datas = DataBaseUtil.GetData(this, JiLuBean.class, " order by _id desc");
        setTitle("扫卡系统"+"("+datas.size()+")");
        jiluAdapter.setDatalist(datas);
    }

    @Override
    public void initListeners() {
        jiluAdapter.setOnItemLongClickListener(new BaseRecycleViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("提示")
                        .setMessage("删除此条记录")
                        .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                JiLuBean jiLuBean = (JiLuBean) jiluAdapter.getDatalist().get(position);
                                jiluAdapter.getDatalist().remove(position);
                                jiluAdapter.notifyDataSetChanged();
                                setTitle("扫卡系统"+"("+jiluAdapter.getDatalist().size()+")");
                                DBHelper db = new DBHelper(MainActivity.this);
                                SQLiteDatabase dataBase = db.getWritableDatabase();
                                try {
                                    dataBase.delete(JiLuBean.class.getSimpleName(), " cardid like ? and time like ?", new String[]{jiLuBean.getCardid(), jiLuBean.getTime()});
                                } catch (Exception e) {
                                    Log.e("SQLite ERROR ", e.getMessage().toString());
                                } finally {
                                    dataBase.close();
                                    db.close();
                                }
                            }
                        }).setNegativeButton("取消", null)
                        .show();
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 当前app正在前端界面运行，这个时候有intent发送过来，那么系统就会调用onNewIntent回调方法，将intent传送过来
        // 我们只需要在这里检验这个intent是否是NFC相关的intent，如果是，就调用处理方法
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            processIntent(intent);
        }
    }

    /**
     * Parses the NDEF Message from the intent and prints to the TextView
     */
    private void processIntent(Intent intent) {
        //取出封装在intent中的TAG
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String CardId = ByteUtil.ByteArrayToHexString(tagFromIntent.getId());
        JiLuBean jiLuBean = new JiLuBean();
        jiLuBean.setCardid(CardId);
        jiLuBean.setTime(TimeUtil.getNowTime());
        jiluAdapter.addItem(0, jiLuBean);
        setTitle("扫卡系统"+"("+jiluAdapter.getDatalist().size()+")");
        DataBaseUtil.saveObjectData(MainActivity.this, JiLuBean.class, jiLuBean);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mNfcAdapter.enableForegroundDispatch(this, pi, null, null);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.items, menu);//获取menu目录下simple.xml的菜单文件
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.out:
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("提示")
                        .setMessage("导出本页数据到excel，请到SD卡中查看[卡号表.xls]")
                        .setPositiveButton("导出", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                // Must be done during an initialization phase like onCreate
                                RxPermissions rxPermissions = new RxPermissions(MainActivity.this); // where this is an Activity instance
                                rxPermissions
                                        .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                                        .subscribe(granted -> {
                                            if (granted) { // Always true pre-M
                                                // I can control the camera now
                                                ExcelUtils.daoChu(jiluAdapter.getDatalist(), "卡号表.xls", MainActivity.this);
                                                DataBaseUtil.clearTable(MainActivity.this, JiLuBean.class);
                                                datas = new ArrayList<Object>();
                                                jiluAdapter.setDatalist(datas);
                                                Toast.makeText(MainActivity.this, "导出成功，请在手机存储下查看此文件", Toast.LENGTH_SHORT).show();
                                            } else {
                                                // Oups permission denied
                                                Toast.makeText(MainActivity.this, "无文件读取权限", Toast.LENGTH_SHORT).show();
                                            }
                                        });
                            }
                        }).setNegativeButton("取消", null)
                        .show();


                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
